
from typing import List
from calendar import month_name
from concurrent.futures import Executor
# from tool import config_manager
import os
import sys
import time
import logging
# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, project_root)
# print(project_root)


from src.backend.anchor_manager import AnchorManager
from src.tools.config_manager import ConfigManager,Host
from src.tools.ssh_connection import SSHConnectionManager
from src.tools.command_executor import CommandExecutor
from src.tools.result_collector import TaskResult

# from src.backend.data_bridge import DataBridge
logger = logging.getLogger(__name__)

class TaskServer:
    def __init__(self):

        self.anchor_register_file = "./src/backend/anchors/anchor_register.yaml"
        self.login_file = "./src/backend/anchors/login.yaml"
        self.anchor_manager = AnchorManager(self.anchor_register_file)
        self.login_config = ConfigManager(self.login_file)
        self.remote_hosts = self.login_config.hosts
        self.local_shell_init_task = self.login_config.tasks[0]
        self.ssh_manager = SSHConnectionManager()
        self.command_executor = CommandExecutor(self.ssh_manager)

    async def login_remote_preset(self):
        await self.command_executor.execute_tasks(self.login_config)


    async def login_remote(self,data:dict) :

        # 1. 解析参数
        name = data.get("name")
        host = data.get("host")
        port = data.get("port")
        username = data.get("username")
        password = data.get("password")
        if not name or not host or not port or not username or not password:
            print("参数错误")
            return False,"参数错误"


        # 2. 检查是否已存在
        key = f"{name}|{host}:{port}|{username}"
        if self.ssh_manager.has_connection(key):
            print("主机已存在")
            return True,"主机已存在"


        host = Host(name=name,host=host,port=port,username=username,password=password)
        
        try:
            # 获取远程连接
            self.ssh_manager.get_connection(host)
            self.login_config.hosts[name] = host
            self.remote_hosts[name] = host

            load_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
            cmd_output_dir = "cmd_output_log/"+"frontend-remotelogin-"+"-"+load_time
            await self.command_executor.ssh_manager_stream.execute_streaming_command(
                host=host,
                task=self.local_shell_init_task,
                cmd_output_dir=cmd_output_dir)

            connection_stats = self.ssh_manager.get_connection_stats()
            print("连接信息:", connection_stats)

            health_check = self.ssh_manager.health_check()
            print("健康检查:", health_check)

            return True,"登录成功"
        except Exception as e:
            logger.error(f"登录失败: {key}, 错误: {e}")
            return False,str(e)


    async def add_command_event(self,data:dict) -> List[TaskResult]:

        # 1. 解析命令
        cmd_event = data.get("cmd_event")
        if not cmd_event:
            print("命令为空")
            none_result = []
            none_result.append(CommandExecutor.create_none_result())
            return none_result
        # 2. 解析参数
        params = data.get("params")
        if not params:
            print("参数为空")
            none_result = []
            none_result.append(CommandExecutor.create_none_result())
            return none_result
        # 3. 解析主机
        hosts_key = data.get("hosts_key")
        if not hosts_key:
            print("主机为空")
            none_result = []
            none_result.append(CommandExecutor.create_none_result())
            return none_result
        
        # 4. 锚点参数注入
        rejected_task_config = self.anchor_manager.inject(cmd_event, params)
        if not rejected_task_config:
            logger.error(f"锚点参数注入失败: {cmd_event}|{params}")
            none_result = []
            none_result.append(CommandExecutor.create_none_result())
            return none_result
        
        print(f"===========rejected_task_config.tasks:================ \n{rejected_task_config.tasks}")

        # 5. 找到key对应的主机配置 
        # 解析"云主机|10.21.162.157:22|本地shell"
        hosts_name = []
        for key in hosts_key:
            hosts_name.append(key.split("|")[0])
        hosts = {}
        for name in hosts_name:
            hosts[name] = self.remote_hosts[name]

        # 6. 执行任务
        results = await self.command_executor.execute_tasks(rejected_task_config,hosts_input=hosts)
        return results
 

    def check_health(self):
        health_check = self.ssh_manager.health_check()
        return health_check
